import { useReducer } from "react";
// React Context + useReducer/useState:
//  对于中小型应用或局部状态管理，React 内置的 Context API 和 useReducer
//  或 useState 钩子结合使用，可以提供一个轻量级的状态管理解决方案，而不需要引入额外的库。
function reducer(state, action) {
  console.log(state, action);
  switch (action.type) {
    case "add":
      return state + 1;
    case "sub":
      return state - 1;
    case "set":
      return (state = Math.random() * 100);
    default:
      return state;
  }
}

const MyRedux = () => {
  const [state, dispatch] = useReducer(reducer, 0);
  const onclick = function (flag) {
    if (flag) {
      dispatch({ type: "add" });
    } else {
      dispatch({ type: "sub" });
    }
  };
  return (
    <div className="list">
      useReducer的使用
      <button onClick={() => onclick(true)}> +1</button>
      <button onClick={() => onclick(false)}> -1</button>
      <button
        onClick={() =>
          dispatch({
            type: "set",
            payload: { type: "minus", value: 100 },
            address: "asdasdads",
          })
        }
      >
        随机数
      </button>
      <h1>当前的值为{state}</h1>
    </div>
  );
};
export default MyRedux;
